/**
 * Created by fangshufeng on 2018/4/22.
 */
import React, {Component} from 'react'

import {Select, Divider, Button, Icon, Input, Alert} from 'antd';
import {connect} from 'react-redux'

import  {addEnvAction,bind_session} from '../redux/app.redux'

const {Option, OptGroup} = Select;
const envObj = {
    'stb': ['stb1', 'stb2', 'stb3', 'stb4', 'stb5', 'stb6', 'stb7', 'stb8'],
    '麦子金服财富': ['NN_sit', 'NN_pre', 'NN_prod'],
    '白领贷': ['BL_sit', 'BL_pre', 'BL_prod'],
    '麦子借款': ['MZJK_sit', 'MZJK_pre', 'MZJK_prod']
};

class AddEnv extends Component {

    constructor(props) {
        super(props);
        this.protocol = 'http://';
        this.domain = '.com';
        this.envTag = '';
        this.envValue = '';
    }

    _valueChange = (key, v) => {
        this[key] = v;
        const submit = [this.envTag, `${this.protocol}${this.envValue}${this.domain}`];
        let emptyIndex = undefined;
        if (this.envTag === '') {
            emptyIndex = 0
        } else if (this.envValue === '') {
            emptyIndex = 2;
        }
        this.props.submitAction(submit[0], submit[1], emptyIndex);
    };

    selectBefore = _ => (
        <Select defaultValue="http://" style={{width: 90}} onChange={(v) => this._valueChange('protocol', v)}>
            <Option value="http://">http://</Option>
            <Option value="https://">https://</Option>
        </Select>
    );

    selectAfter = _ => (
        <Select defaultValue=".com" style={{width: 80}} onChange={(v) => this._valueChange('domain', v)}>
            <Option value=".com">.com</Option>
            <Option value=".jp">.jp</Option>
            <Option value=".cn">.cn</Option>
            <Option value=".org">.org</Option>
        </Select>
    );

    render() {
        return <div
            style={{...this.props.style, display: 'flex', flexDirection: 'row', justifyContent: 'space-around'}}>
            <Input placeholder='环境名称' style={{width: 80, marginRight: 10}}
                   onChange={(v) => this._valueChange('envTag', v.target.value)}/>
            <Input addonBefore={this.selectBefore()} addonAfter={this.selectAfter()}
                   onChange={(v) => this._valueChange('envValue', v.target.value)}/>
            <Button icon="minus-circle" type='danger' style={{marginLeft: 10}} onClick={() => this.props.delete()}/>
        </div>
    }
}

class EnvSelect extends Component {

    constructor(props) {
        super(props);
        this.state = {
            showAddEnv: false,
            errorMsg: undefined,
        }
        ;
        this.env = '';
        this.envValue = '';
        this.errorMsg = undefined;
    }

    componentDidMount() {
        if (this.props.socketID === '') {
            this.props.bind_session();
        }
    }
    render() {
        const {showAddEnv, errorMsg} = this.state;
        return <div style={style.contanier}>
            <div style={style.selectContanier}>
                <div style={{marginTop:10}}><h2 style={{textAlign: 'center'}}>环境选择</h2></div>
                <Divider dashed/>
                <Select
                    placeholder="请选择需要mock的环境"
                    defaultValue={undefined}
                    style={{width: '80%'}}
                    onChange={(v) => {
                        style.selectContanier = {...style.selectContanier, height: 200};
                        this.setState({
                            errorMsg: undefined,
                            showAddEnv: false
                        });
                        this.env = v;
                    }}
                    size="large"
                >
                    {Object.keys(envObj).map(v => (<OptGroup key={v} label={<h3>{v}</h3>}>
                        {envObj[v].map((value, index) => (<Option value={value} key={value + index}>{value}</Option>))}
                    </OptGroup>))}
                </Select>

                {showAddEnv ? <AddEnv style={{width: '80%', marginLeft: '10%', marginTop: 20}}
                                      submitAction={(tag, v, emptyIndex) => {
                                          this.envValue = v;
                                          this.env = tag;
                                          if (emptyIndex === 0) {
                                              this.errorMsg = '环境名称未填写';
                                          } else if (emptyIndex === 2) {
                                              this.errorMsg = '主机名不能为空';
                                          } else {
                                              this.errorMsg = undefined;
                                          }
                                      }}
                                      delete={() => {
                                          style.selectContanier = {...style.selectContanier, height: 200};
                                          this.setState({
                                              errorMsg: undefined,
                                              showAddEnv: false
                                          });
                                      }
                                      }/> : null}
                { errorMsg !== undefined ? <Alert message={errorMsg} type="error" showIcon/> : null}
                <div style={style.footStyle}>
                    <Button type="dashed" style={{width: '30%'}} disabled={showAddEnv}
                            onClick={() => {
                                style.selectContanier = {...style.selectContanier, height: 300};
                                this.errorMsg = '环境名称未填写';
                                this.setState({showAddEnv: true })
                            }
                            }>
                        <Icon type="plus"/> 新增环境
                    </Button>
                    <Button type="primary"
                            onClick={() => {

                                const {showAddEnv} = this.state;
                                if (showAddEnv) {
                                    if (this.errorMsg !== undefined) {
                                        return this.setState({
                                            errorMsg: this.errorMsg,
                                        }); 
                                    }
                                } else {
                                    if (this.env === '') {
                                        style.selectContanier = {...style.selectContanier, height: 250};
                                        this.setState({
                                            errorMsg: '请选择环境',
                                        });
                                        return;
                                    }
                                }
                                this.props.addEnvAction(this.env, this.envValue, showAddEnv);
                                style.selectContanier = {...style.selectContanier, height: 200};
                                this.props.history.push('/mockTool/bindDevice');
                            }}
                            style={{width: '30%'}}>
                        确定选择
                    </Button>
                </div>
            </div>

        </div>;
    }
}

const style = {

    contanier: {
        backgroundColor: '#585858',
        width: '100%',
        height: '100%',
        position: 'fixed',
        // alignItems:'center',
        display: 'flex',
        justifyContent: 'center',
        background:`url('/img/back.jpg')`,
        backgroundRepeat:'round'
    },
    selectContanier: {
        backgroundColor: 'white',
        width: 550,
        marginTop: 200,
        height: 200,
        borderRadius: 3,
        textAlign: 'center'
    },
    footStyle: {
        display: 'flex',
        justifyContent: 'space-between',
        marginLeft: '10%',
        marginTop: 20,
        marginRight: '10%'
    }
};

export default connect(state => state.app, {addEnvAction,bind_session})(EnvSelect);